package hight;

import java.util.concurrent.locks.ReentrantReadWriteLock;

public class ReentrantReadWriteLockTest {
    // ReentrantReadWirteLock 读写锁，采用读写分离机制，高并发下都读多写少时性能优于ReentrantLock
    // 读读共享，写写互斥，读写互斥
    private ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();
    private ReentrantReadWriteLock.ReadLock readLock = rwlock.readLock();
    private ReentrantReadWriteLock.WriteLock writeLock = rwlock.writeLock();

    public void read() {
        try {
            readLock.lock();
            System.out.println("当前线程：" + Thread.currentThread().getName() + " read进入");

            Thread.sleep(3000);
            System.out.println("当前线程：" + Thread.currentThread().getName() + "read退出...");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            readLock.unlock();
        }


    }
    public void write() {
        try {
            writeLock.lock();
            System.out.println("当前线程：" + Thread.currentThread().getName() + " write进入");

            Thread.sleep(3000);
            System.out.println("当前线程：" + Thread.currentThread().getName() + "write退出...");

        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            writeLock.unlock();
        }
    }

    public static void main(String[] args) {
        final ReentrantReadWriteLockTest t = new ReentrantReadWriteLockTest();
        Thread t1 = new Thread(()->{
            t.read();
        },"t1");
        Thread t2 = new Thread(()->{
            t.read();
        },"t2");
        Thread t3 = new Thread(()->{
            t.write();
        },"t3");
        Thread t4 = new Thread(()->{
            t.write();
        },"t4");
        t1.start();
        t2.start();
        t3.start();
        t4.start();
    }
}
